<template>
  <div class="doctor-list-container">
      <TopHeader />
      <BottomNavigation />
    
    <!-- 移动端搜索与排序 -->
    <div class="mobile-top-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索医生姓名"
        prefix-icon="el-icon-search"
        class="mobile-search-input"
        @keyup.enter="fetchDoctors"
      />
      <el-select
        v-model="sortType"
        placeholder="排序"
        class="mobile-sort-select"
        @change="fetchDoctors"
      >
        <el-option
          v-for="(option, idx) in sortOptions"
          :key="idx"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>
    
    <!-- 加载状态显示 -->
    <div v-if="isLoading" class="loading-container">
      <el-skeleton :rows="5" active />
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert type="error" :title="errorMessage" />
    </div>
    
    <!-- 医生列表 -->
    <div v-else class="doctor-main" style="margin-bottom: 100px;"> <!-- 新增margin-bottom -->
      <div v-if="doctors.length === 0" class="empty-list">
        <el-empty description="未找到符合条件的医生" />
      </div>
      <div v-else class="doctor-list">
        <el-card
          v-for="(doctor, index) in filteredDoctors"
          :key="doctor.doc_id"
          class="doctor-card"
        >
          <template #header>
            <div class="doctor-info-header">
              <span class="doctor-name">{{ doctor.doc_name }}</span>
              <el-tag :type="getTagType(doctor.doc_title)">{{ doctor.doc_title }}</el-tag>
            </div>
          </template>
          <div class="doctor-content">
            <el-image
              :src="doctor.avatar || 'https://picsum.photos/200/200?random=' + doctor.doc_id"
              class="doctor-avatar"
              fit="cover"
            />
            <div class="doctor-desc">
              <p class="doctor-skills">擅长：{{ doctor.introduction || '暂无擅长领域信息' }}</p>
              <p class="doctor-rating">
                <span class="star-icon" v-for="n in 5" :key="n">
                  {{ n <= (doctor.rating || 3) ? '★' : '☆' }}
                </span>
                {{ doctor.rating || 3.0 }} ({{ doctor.evaluateCount || 0 }}评价)
              </p>
              <p class="doctor-bio">{{ doctor.introduction || '暂无医生简介' }}</p>
              <p class="doctor-schedule">
                出诊时间：{{ doctor.schedule || '暂无出诊信息' }} <br />
                挂号费：{{ doctor.fee || '¥0.00' }}
              </p>
              <el-button type="primary" class="reserve-btn" @click="handleReserve(doctor)">
                立即预约
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElInput, ElSelect, ElOption, ElCard, ElTag, ElImage, ElButton, ElSkeleton, ElEmpty, ElAlert } from 'element-plus';
import axios from 'axios';
import BottomNavigation from '@/components/BottomNavigation.vue';
import TopHeader from '@/components/TopHeader.vue';

// 配置API基础URL，根据实际后端地址修改
const apiBaseUrl = 'http://localhost:8080/hospital5_war/doctor';

// 状态管理
const doctors = ref([]);
const searchKeyword = ref('');
const sortOptions = ref([
  { label: '推荐医生', value: 'recommend' },
  { label: '评分最高', value: 'ratingDesc' },
  { label: '挂号费最低', value: 'feeAsc' }
]);
const sortType = ref('recommend');
const isLoading = ref(true);
const errorMessage = ref('');

// 从API获取医生列表
const fetchDoctors = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    // 调用后端API获取所有医生
    const response = await axios.get(`${apiBaseUrl}/findAll`);
    const doctorData = response.data;
    
    // 处理排序
    let sortedDoctors = [...doctorData];
    if (sortType.value === 'ratingDesc') {
      sortedDoctors.sort((a, b) => (b.rating || 0) - (a.rating || 0));
    } else if (sortType.value === 'feeAsc') {
      sortedDoctors.sort((a, b) => {
        const feeA = parseFloat((a.fee || '¥0.00').replace('¥', ''));
        const feeB = parseFloat((b.fee || '¥0.00').replace('¥', ''));
        return feeA - feeB;
      });
    }
    
    doctors.value = sortedDoctors;
  } catch (error) {
    console.error('获取医生数据失败:', error);
    errorMessage.value = '获取医生数据失败，请稍后再试';
  } finally {
    isLoading.value = false;
  }
};

// 根据职称设置Tag类型
const getTagType = (title) => {
  if (title.includes('主任')) return 'success';
  if (title.includes('副主任')) return 'info';
  return 'primary';
};

// 筛选后的医生列表
const filteredDoctors = computed(() => {
  if (!searchKeyword.value) {
    return doctors.value;
  }
  
  return doctors.value.filter(doctor => 
    (doctor.doc_name || '').includes(searchKeyword.value)
  );
});

// 处理预约逻辑
const handleReserve = (doctor) => {
  console.log('预约医生:', doctor);
  // 这里可以添加预约逻辑，例如跳转到预约页面
  // router.push(`/reservation/${doctor.doc_id}`);
};

// 组件挂载时获取医生数据
onMounted(() => {
  fetchDoctors();
});

// 组件卸载时清理
onUnmounted(() => {
  // 可以在这里添加清理逻辑
});
</script>

<style scoped>
.doctor-list-container {

  padding-top: 70px; /* 减小标题下方空白，可根据实际需求微调 */
}

.doctor-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
}
.doctor-card-header .doctor-name {
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap; /* 姓名不换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出部分显示省略号，若要完整显示可去掉这行 */
  max-width: 60%; /* 限制姓名区域宽度，避免挤压其他元素，可按需调整 */
}

/* 调整搜索框、筛选框与标题的间距 */
.mobile-top-bar {
  margin-top: 8px; /* 减小与上方标题的间距 */
}

/* 移动端顶部搜索排序 */
.mobile-top-bar {
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 60px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.mobile-search-input {
  width: 100% !important;
}

.mobile-sort-select {
  width: 100% !important;
}

/* 加载状态样式 */
.loading-container {
  padding: 20px;
}

/* 错误提示样式 */
.error-message {
  padding: 20px;
}

/* 空列表样式 */
.empty-list {
  padding: 40px 20px;
  text-align: center;
}

/* 医生卡片 */
.doctor-card {
  margin-bottom: 15px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.doctor-info-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.doctor-name {
  font-size: 16px;
  font-weight: 600;
}

.doctor-content {
  display: flex;
  padding: 15px;
}

.doctor-avatar {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 8px;
}

.doctor-desc {
  flex: 1;
}

.doctor-skills {
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
}

.doctor-rating {
  color: #f90;
  margin-bottom: 8px;
  font-size: 14px;
}

.star-icon {
  margin-right: 2px;
  font-size: 14px;
}

.doctor-bio {
  color: #999;
  margin-bottom: 8px;
  line-height: 1.4;
  font-size: 13px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.doctor-schedule {
  color: #666;
  margin-bottom: 12px;
  line-height: 1.6;
  font-size: 14px;
}

.reserve-btn {
  margin-top: 8px;
  padding: 8px 12px;
  font-size: 13px;
}

/* 响应式布局 - 桌面端 */
@media (min-width: 768px) {
  .doctor-main {
    padding: 20px;
  }
  
  .mobile-top-bar {
    flex-direction: row;
    justify-content: space-between;
    padding: 20px;
  }
  
  .mobile-search-input {
    width: 300px !important;
  }
  
  .mobile-sort-select {
    width: 150px !important;
  }
  
  .doctor-card {
    margin-bottom: 20px;
  }
  
  .doctor-name {
    font-size: 18px;
  }
  
  .doctor-avatar {
    width: 120px;
    height: 120px;
  }
  
  .doctor-skills,
  .doctor-rating {
    font-size: 16px;
  }
  
  .doctor-bio {
    font-size: 14px;
  }
  
  .reserve-btn {
    padding: 10px 16px;
    font-size: 14px;
  }
}
</style>